package com.gs;

import com.gs.common.core.redis.RedisCache;
import com.gs.common.utils.token.AccToken;
import com.gs.common.utils.token.JwtTokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
@ConfigurationProperties(prefix = "unauth")
public class AuthFilter implements GlobalFilter, Ordered {
    private List<String> urls;
    public void setUrls(List<String> urls){
        this.urls=urls;
    }
//    private List<String> weburls;
//    public void setWeburls(List<String> urls){
//        this.weburls=weburls;
//    }
    @Resource
    private RedisCache redisCache;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getPath().toString();
        if(urls.contains(url)){
            return chain.filter(exchange);
        }

        String authorization = exchange.getRequest().getHeaders().getFirst("Authorization");
        //没有token
        if(StringUtils.isEmpty(authorization)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        //解密
        String jwt = authorization.substring(7);
        AccToken accToken =null;
//        if(weburls.contains(url)){
            //前端请求
            accToken = JwtTokenUtils.parseWebToken(jwt);
            if (Objects.isNull(accToken)) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            String tokenInRedis = redisCache.getCacheObject(jwt);
            if(StringUtils.isNotEmpty(tokenInRedis)){
                redisCache.setCacheObject(jwt,jwt,30, TimeUnit.MINUTES);
            }else{
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            return chain.filter(exchange);
//        }
        //后台前端请求
//        accToken = JwtTokenUtils.parseToken(jwt);
//        if(Objects.isNull(accToken)){
//            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//            return exchange.getResponse().setComplete();
//        }
        //放行
//        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
